import React, { PureComponent } from 'react';
import { Button } from 'antd';
import { isAuthMenuByConfig } from '/common/components/SiderMenu/SiderMenuUtils';
import { connect } from 'dva';
import { getConfigByKeyValue } from '@/appConfig';
import { isEmpty } from 'lodash';

export class ButtonClass extends PureComponent {

  getRestProps() {
    const { appCode, btnType, children, appConfigObj, actionType, dispatch, userInfo, ...restProps } = this.props;
    return restProps;
  }

  noAuthRender() {
    return null;
  }

  mainRender() {
    const { btnType, children } = this.props;
    const restProps = this.getRestProps();

    if ('a' === btnType) {
      return <a href={'javascript:;'} {...restProps}>{children}</a>;

    } else {
      return <Button {...restProps}>{children}</Button>;
    }
  }

  render() {
    // 判断是否有权限
    let hadAuth = true;
    const userInfo = this.props.userInfo || {};
    const appConfigObj = !isEmpty(this.props.appConfigObj) ?
      this.props.appConfigObj : getConfigByKeyValue('appCode', this.props.appCode);

    if (userInfo.resources && appConfigObj && this.props.actionType) {
      const actionType = this.props.actionType;
      const appAuthConfig = appConfigObj.authConfig || {};
      const actionTypeVal = appAuthConfig.actionTypes ? appAuthConfig.actionTypes[actionType] : '';
      const authConfig = { ...appAuthConfig, actionTypes: {} };
      authConfig.actionTypes[actionType] = actionTypeVal;
      hadAuth = isAuthMenuByConfig(authConfig, userInfo.resources || {});
    }

    if (!hadAuth) return this.noAuthRender();

    return this.mainRender();
  }
}

/**
 * 支持 Button 组件的所有属性
 * @type {{actionType: string, appConfigObj: {}}}
 */
ButtonClass.defaultProps = {
  appConfigObj: {}, // Object appConfig 中的配置对象数据
  actionType: '', // String 操作类型
  btnType: 'btn', // String 按钮类型，'btn': <Button></Button>类型; 'a': <a></a> 类型
};

ButtonClass.getConnectData = ({ global: { appCode, userInfo } }) => ({
  appCode,
  userInfo,
});

const ButtonComp = connect(ButtonClass.getConnectData)(ButtonClass);

export default ButtonComp;
